package com.imooc.o2o.service.impl;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.o2o.cache.JedisUtil;
import com.imooc.o2o.dao.HeadLineDao;
import com.imooc.o2o.entity.HeadLine;
import com.imooc.o2o.service.HeadLineService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class HeadLineServiceTest implements HeadLineService {

    @Autowired
    private HeadLineDao headLineDao;

    @Autowired
    private JedisUtil.Keys jedisKeys;

    @Autowired
    private JedisUtil.Strings jedisStrings;

    private static Logger logger = LoggerFactory.getLogger(HeadLineServiceTest.class);

    @Override
    public List<HeadLine> getHeadLineList(HeadLine headLineConddition) throws IOException {
        String key = HEADLINELIST;
        List<HeadLine> headLineList = null;
        ObjectMapper mapper = new ObjectMapper();
        if (headLineConddition != null && headLineConddition.getEnableStatus() != null) {
            key = key + "_" + headLineConddition.getEnableStatus();
        }

        if (!jedisKeys.exists(key)) {
            headLineList = headLineDao.queryHeadLine(headLineConddition);
            String jsonString;
            jsonString = mapper.writeValueAsString(headLineList);
            jedisStrings.set(key, jsonString);
        } else {
            String jsonString = jedisStrings.get(key);
            JavaType javaType = mapper.getTypeFactory()
                    .constructParametricType(ArrayList.class, HeadLine.class);
            headLineList = mapper.readValue(jsonString, javaType);
        }
        return headLineList;
    }
}
